package com.demo.util;

import lombok.extern.slf4j.Slf4j;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Field;

@Slf4j
public class ProcessPid {
    public static void main(String[] args) {

    }

    /**
     * 脚本执行 String command = Gather.DATAX_SHELL_PATH;
     *
     * @param args    参数
     * @param command 脚本
     * @return 执行返回的状态 0 成功 否则失败
     */
    public int exec(String args, String command) {
        int status = -1;
        log.info("exec command:[{}] args=[{}]", command, args);
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(command + " " + args);
            Field field =process.getClass().getDeclaredField("handle");
            field.setAccessible(true);
        } catch (Exception e) {
            log.error("exec command:[{}] failed hasExit=[{}]", command, status, e);
        }
        return status;
    }

    private static int getPid() {
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        String name = runtime.getName(); // format: "pid@hostname"
        try {
            return Integer.parseInt(name.substring(0, name.indexOf('@')));
        } catch (Exception e) {
            return -1;
        }
    }
}
